package com.guli.vod.controller;

import com.aliyun.oss.OSS;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.guli.common.handler.EduException;
import com.guli.common.result.R;
import com.guli.vod.handler.OSSValueUtils;
import com.guli.vod.service.VideoService;
import com.guli.vod.utils.AliyunVodSDKUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Api(description="阿里云视频点播微服务")
@CrossOrigin //跨域
@RestController
@RequestMapping("/admin/vod/video")
public class VideoAdminController {

    @Autowired
    private VideoService videoService;

    @ApiOperation("根据视频id获取视频播放凭证")
    @GetMapping("getPlayAuth/{videoId}")
    public R getVideoPlayAuth(@PathVariable String videoId){
        //初始化客户端、请求对象和相应对象
        DefaultAcsClient client = OSSValueUtils.initVodClient(OSSValueUtils.ACCESS_KEY_ID, OSSValueUtils.ACCESS_KEY_SECRET);
        GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
        GetVideoPlayAuthResponse response ;

        try {
            //设置请求参数
            request.setVideoId(videoId);
            //获取请求响应
            response = client.getAcsResponse(request);
            //设置播放凭证的有效期 默认为100秒
            request.setAuthInfoTimeout(1000L);
            //输出请求结果
            String playAuth = response.getPlayAuth();
            return R.ok().data("playAuth",playAuth);
        } catch (Exception e) {
            throw new EduException(200001,"获取播放品证异常");
        }
    }

    @ApiOperation("根据id删除音视频")
    @DeleteMapping("{videoId}")
    public R removeVideo(@ApiParam(name = "videoId", value = "云端视频id", required = true) @PathVariable String videoId){
        videoService.removeVideo(videoId);
        return R.ok().message("视频删除成功");
    }

    @ApiOperation("批量删除视频")
    @DeleteMapping("delete-batch")
    public R  removeVideoList(
            @ApiParam(name = "videoIdList", value = "云端视频id", required = true)
            @RequestParam("videoIdList") List videoIdList){
        videoService.removeVideoList(videoIdList);
        return R.ok().message("视频删除成功");
    }

    @ApiOperation("上传音视频")
    @PostMapping("upload")
    public R uploadVideo(
            @ApiParam(name = "file", value = "文件", required = true)
            @RequestParam("file") MultipartFile file) throws Exception {

        String videoId = videoService.uploadVideo(file);
        return R.ok().message("视频上传成功").data("videoId", videoId);
    }


}
